package com.czkj.hwz.decorate.Activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.czkj.hwz.decorate.R;
import com.czkj.hwz.decorate.database.RecordSQLiteOpenHelper;
import com.czkj.hwz.decorate.view.banner.SearchListView;
import com.king.base.BaseActivity;
import com.king.base.util.ToastUtils;

public class SearchActivity extends BaseActivity {
    private Spinner spinnerType;
    private String[] arrayTypes;
    private SearchListView listView;
    private BaseAdapter adapter;
    // 数据库变量
    // 用于存放历史搜索记录
    private RecordSQLiteOpenHelper helper ;
    private SQLiteDatabase db;
    private Button searchbt;
    private TextView tv_clear;  // 删除搜索记录按键
    private EditText search_text;
    private TextView history_search_tv;
    private int num;
    @Override
    public void initUI() {
        if (Build.VERSION.SDK_INT >= 21){
            Window window = getWindow();
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.yellow));
        }
        setContentView(R.layout.activity_search);
        getSupportActionBar().hide();
        search_text=findView(R.id.search_text);
        spinnerType=findView(R.id.spinner_type);
        listView=findView(R.id.listView);
        history_search_tv=findView(R.id.history_search_tv);
        searchbt=findView(R.id.search);
        tv_clear=findView(R.id.tv_clear);
        tv_clear.setVisibility(View.INVISIBLE);
        history_search_tv.setVisibility(View.INVISIBLE);
        arrayTypes=new String[] {"商品","监理","工人","家装公司"};
        helper = new RecordSQLiteOpenHelper(context);
        queryData("");
    }

    @Override
    public void initData() {
        ArrayAdapter adapter=new ArrayAdapter(this,R.layout.simple_spinner_item,arrayTypes);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerType.setAdapter(adapter);


    }
    private void queryData(String tempName) {



        // 1. 模糊搜索
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
        // 2. 创建adapter适配器对象 & 装入模糊搜索的结果
        adapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
                new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        // 3. 设置适配器
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        System.out.println(cursor.getCount());
        // 当输入框为空 & 数据库中有搜索记录时，显示 "删除搜索记录"按钮
        if (tempName.equals("") && cursor.getCount() != 0){
            tv_clear.setVisibility(View.VISIBLE);
            history_search_tv.setVisibility(View.VISIBLE);
        }
        else {
            tv_clear.setVisibility(View.INVISIBLE);
            if (cursor.getCount()==0) {
                history_search_tv.setVisibility(View.INVISIBLE);
            }else {

            }
        }


    }
    @Override
    public void addListeners() {
        searchbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goActivity();
            }
        });
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清空数据库->>关注2
                deleteData();
                // 模糊搜索空字符 = 显示所有的搜索历史（此时是没有搜索记录的）
                queryData("");
            }
        });
        search_text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_SEARCH) {
                    goActivity();
                }
                return false;
            }
        });
        search_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            // 输入文本后调用该方法
            @Override
            public void afterTextChanged(Editable s) {
                // 每次输入后，模糊查询数据库 & 显示
                // 注：若搜索框为空,则模糊搜索空字符 = 显示所有的搜索历史
                String tempName = search_text.getText().toString();
                queryData(tempName); // ->>关注1
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // 获取用户点击列表里的文字,并自动填充到搜索框内
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                search_text.setText(name);
            }
        });
        spinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                num=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
    /**
     * 关注3
     * 检查数据库中是否已经有该搜索记录
     */
    private boolean hasData(String tempName) {
        // 从数据库中Record表里找到name=tempName的id
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //  判断是否有下一个
        return cursor.moveToNext();
    }
    /**
     * 关注4
     * 插入数据到数据库，即写入搜索字段到历史搜索记录
     */
    private void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }
    private void deleteData() {

        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
        tv_clear.setVisibility(View.INVISIBLE);
        history_search_tv.setVisibility(View.INVISIBLE);
    }
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

        }
    }

    private void goActivity() {
        Intent intent;
        if (TextUtils.isEmpty(search_text.getText().toString())) {
            ToastUtils.showToast(context,"请输入关键字");
        }else {
            // 2. 点击搜索键后，对该搜索字段在数据库是否存在进行检查（查询）->> 关注1
            boolean hasData = hasData(search_text.getText().toString().trim());
            // 3. 若存在，则不保存；若不存在，则将该搜索字段保存（插入）到数据库，并作为历史搜索记录
            if (!hasData) {
                insertData(search_text.getText().toString().trim());
                queryData("");
            }
            switch (num) {
                case 0:
                    intent=new Intent(context,ProductActivity.class);
                    intent.putExtra("keyword",search_text.getText().toString().trim());
                    startActivity(intent);
                    break;
                case 1:
                    intent=new Intent(context,SupervisorSearchActivity.class);
                    intent.putExtra("keyword",search_text.getText().toString().trim());
                    startActivity(intent);
                    break;
                case 2:
                    intent=new Intent(context,WorkerSearchActivity.class);
                    intent.putExtra("keyword",search_text.getText().toString().trim());
                    startActivity(intent);
                    break;
                case 3:
                    intent=new Intent(context,HomeDecorationActivity.class);
                    intent.putExtra("keyword",search_text.getText().toString().trim());
                    startActivity(intent);
                    break;
            }
        }
    }
}
